package com.huike.framework.web.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.huike.common.constant.Constants;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.core.redis.RedisCache;
import com.huike.common.exception.CustomException;
import com.huike.common.exception.user.CaptchaException;
import com.huike.common.exception.user.CaptchaExpireException;
import com.huike.common.exception.user.UserPasswordNotMatchException;
import com.huike.common.utils.MessageUtils;
import com.huike.framework.manager.AsyncManager;
import com.huike.framework.manager.factory.AsyncFactory;

/**
 * 登录校验方法
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        //验证码key,此处的uuid获取验证码时返回前端的验证码UUID
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        //验证码结果
        //String captcha = redisCache.getCacheObject(verifyKey);
        //快速登录后门
        String captcha = code;
        //验证成功删除Redis缓存
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            //开启一个异步的子线程，不会影响主线程执行
            //主线程先子线程执行完
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        //封装用户用户名和密码
        Authentication authentication = null;
        try {
            /**
             * ！！！看我看我看我！！！
             * 看我少走弯路，获取用户对象的时候，会去调用下面的这个方法查询用户对象
             * UserDetailsServiceImpl.loadUserByUsername
             */
            System.out.println("username " + username + " -----password " + password);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            //该方法会自动调用UserDetailsServiceImpl.loadUserByUsername，判断用户账号状态是否正常
            /* w:在封装用户名等数据后，调用ProviderManager中的authenticate方法进行认证，认证后存入loginUser信息
                 所以需要在SecurityConfig中配置AuthenticationManager的getBean方法，使其能够被springboot自动注入*/
            /*框架自动调用DaoAuthenticationProvider.additionalAuthenticationChecks()方法完成密码校验*/
            authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        //通过debug的方式找到authentication中存放userID的位置
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }
}
